package cn.yunyichina.provider.pay.service;

import cn.yunyichina.provider.pay.entity.PaymentSetting;
import cn.yunyichina.provider.pay.exception.PaySettingNotFoundException;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lullaby on 2016/11/5.
 */
public class BaseOpenidService extends BaseService {

    protected boolean checkOpenidParameters(Map<String, String> params) {
        if (StringUtils.isEmpty(params.get("auth_code")) ||
                StringUtils.isEmpty(params.get("app_id"))) {
            return false;
        }

        return true;
    }

    protected Map<String, String> buildWechatAuthParameters(Map<String, String> params) throws PaySettingNotFoundException {
        Map<String, String> result = new HashMap<>();

        PaymentSetting paymentSetting = this.getPaymentSetting(params.get("app_id"));

        result.put("app_id", params.get("app_id"));
        result.put("app_secret", paymentSetting.getSecretKey());
        result.put("auth_code", params.get("auth_code"));

        return result;
    }

    protected Map<String, String> buildWechatAppletOpenidParameters(Map<String, String> params) throws PaySettingNotFoundException {
        Map<String, String> result = new HashMap<>();

        PaymentSetting paymentSetting = this.getPaymentSetting(params.get("app_id"));

        result.put("appid", params.get("app_id"));
        result.put("secret", paymentSetting.getSecretKey());
        result.put("js_code", params.get("auth_code"));
        result.put("grant_type", "authorization_code");

        return result;
    }

    protected Map<String, String> buildAlipayAuthParameters(Map<String, String> params) throws PaySettingNotFoundException {
        Map<String, String> result = new HashMap<>();

        PaymentSetting paymentSetting = this.getPaymentSetting(params.get("app_id"));
        String signType = "RSA";
        if (paymentSetting.getPayPublicKey().length() > 256) {
            signType = "RSA2";
        }

        result.put("app_id", params.get("app_id"));
        result.put("auth_code", params.get("auth_code"));
        result.put("pay_public_key", paymentSetting.getPayPublicKey());
        result.put("public_key", paymentSetting.getPublicKey());
        result.put("private_key", paymentSetting.getPrivateKey());
        result.put("sign_type", signType);

        return result;
    }

}
